package com.ruoyi.dmsIms.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.dmsIms.domain.TestFile;
import com.ruoyi.dmsIms.service.ITestFileService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 测试文件Controller
 * 
 * @author ZhangSiRui
 * @date 2022-01-04
 */
@Slf4j
@RestController
@RequestMapping("/dmsIms/file")
public class TestFileController extends BaseController
{
    @Autowired
    private ITestFileService testFileService;

    /**
     * 查询测试文件列表
     */
    @PreAuthorize("@ss.hasPermi('dmsIms:file:list')")
    @GetMapping("/list")
    public TableDataInfo list(TestFile testFile)
    {
        startPage();
        List<TestFile> list = testFileService.selectTestFileList(testFile);
        return getDataTable(list);
    }

    /**
     * 导出测试文件列表
     */
    @PreAuthorize("@ss.hasPermi('dmsIms:file:export')")
    @Log(title = "测试文件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TestFile testFile)
    {
        List<TestFile> list = testFileService.selectTestFileList(testFile);
        ExcelUtil<TestFile> util = new ExcelUtil<TestFile>(TestFile.class);
        util.exportExcel(response, list, "测试文件数据");
    }

    /**
     * 获取测试文件详细信息
     */
    @PreAuthorize("@ss.hasPermi('dmsIms:file:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(testFileService.selectTestFileById(id));
    }

    /**
     * 获取测试文件详细信息
     */
    @PreAuthorize("@ss.hasPermi('dmsIms:file:query')")
    @GetMapping(value = "fileCheck/{id}")
    public AjaxResult getFileExist(@PathVariable("id") Long id)
    {
        TestFile testFile = testFileService.selectTestFileById(id);
        String path = FileUploadUtils.getDefaultBaseDir() + "/" + testFile.getFilePath();
        File file = new File(path);
        if (file.exists()){
            return AjaxResult.success();
        }else {
            return AjaxResult.error("文件不存在");
        }

    }

    /**
     * 新增测试文件
     */
    @PreAuthorize("@ss.hasPermi('dmsIms:file:add')")
    @Log(title = "测试文件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TestFile testFile)
    {
        return toAjax(testFileService.insertTestFile(testFile));
    }

    /**
     * 修改测试文件
     */
    @PreAuthorize("@ss.hasPermi('dmsIms:file:edit')")
    @Log(title = "测试文件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TestFile testFile)
    {
        return toAjax(testFileService.updateTestFile(testFile));
    }

    /**
     * 删除测试文件
     */
    @PreAuthorize("@ss.hasPermi('dmsIms:file:remove')")
    @Log(title = "测试文件", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(testFileService.deleteTestFileByIds(ids));
    }


    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(MultipartFile file) throws IOException {
        String res = FileUploadUtils.upload(file);
        if (res == null){
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    @PostMapping("/uploadFiles")
    public AjaxResult uploadFiles(MultipartFile[] file) throws IOException {
        List<Map<String,String>> paths;
        if(file != null){
            for (MultipartFile file1:
                    file) {
                String fileName = FileUploadUtils.dmsUpload(file1);
                String filePath = FileUploadUtils.getFilePath();
                String extension = FileUploadUtils.getExtension(file1);
                TestFile testFile = new TestFile();
                testFile.setFileName(fileName);
                testFile.setFileType(extension);
                testFile.setFilePath(filePath);
                testFileService.insertTestFile(testFile);
            }
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }

    @GetMapping("/download/{id}")
    public void download(@PathVariable("id") Long id, HttpServletResponse response) throws UnsupportedEncodingException {
        TestFile testFile = testFileService.selectTestFileById(id);
        String fileName = testFile.getFileName();
        String path = FileUploadUtils.getDefaultBaseDir()+"/"+testFile.getFilePath();
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", fileName));
            }
            // 本地资源路径
//            String localPath = RuoYiConfig.getProfile();//这里的getProfile不
//            // 数据库资源地址
//            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            //String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            //response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);//二进制文件
            response.setHeader("Content-Disposition", "attachment; filename="+fileName);
            response.setContentType("application/octet-stream; charset=UTF-8");
            FileUtils.setAttachmentResponseHeader(response, fileName);
            System.out.println("downloadPath:"+path);
            FileUtils.writeBytes(path, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

}
